from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.http import JsonResponse
from django.shortcuts import redirect, get_object_or_404
from django.urls import reverse
from django.urls import reverse_lazy
from django.views.generic import ListView, UpdateView, DeleteView, CreateView, DetailView

from ChanPin.models import Dingdan
from TuiGuang.models import tg_qudao
from jiaowu_xueyuan.forms import Xueyuan_zongbiao_form,Xueyuan_zongbiao
from jiaowu_xueyuan.models import xueyuan_jiaowu_genjinlog
from .forms import KeHuForm, KeHuzilaoForm, KeHugenjinlogForm, KeHu_zhaungtaiForm
from .models import KeHu, KeHuzilao, KeHugenjinlog, KeHu_zhaungtai
from qxcrm_index.utils import search_kehu # 导入search_kehu函数客户搜索功能

from qxcrm_index.tool_user_zhanneixin import zhanneixin_index # 引入zhanneixin_index函数 站内信


class KeHuCreateView(LoginRequiredMixin, CreateView):
    """创建新的客户"""
    bigtitle = "客户管理"
    model = KeHu
    form_class = KeHuForm
    template_name = 'kehu_add.html'
    success_url = reverse_lazy('kehu_list')


    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['bigtitle'] = self.bigtitle
        if 'kehu_zhaungtai_form' not in context:
            context['kehu_zhaungtai_form'] = KeHu_zhaungtaiForm(self.request.POST or None)
        if 'kehu_ziliao_form' not in context:
            context['kehu_ziliao_form'] = KeHuzilaoForm(self.request.POST or None)
        return context

    def form_valid(self, form):
        context = self.get_context_data()
        kehu_zhaungtai_form = context['kehu_zhaungtai_form']
        kehu_ziliao_form=context['kehu_ziliao_form']
        self.object = form.save()
        if kehu_zhaungtai_form.is_valid():
            ###自动添加一个客户状态的表单实例并保存均为空
            kehu_zhaungtai_form.instance.kehu = self.object
            kehu_zhaungtai_form.save()
        if kehu_ziliao_form.is_valid():
            ###自动添加一个客户资料的表单实例并保存均为空
            kehu_ziliao_form.instance.kehu = self.object
            kehu_ziliao_form.save()
        current_user = self.request.user
        context['current_user'] = current_user
        # 设置admin_user字段的值
        self.object = form.save(commit=False)
        self.object.admin_user = current_user  # 设置额外字段的值
        self.object.save()

        return super().form_valid(form)

class KehuDeleteView(LoginRequiredMixin, DeleteView):
    model = KeHu
    success_url = 'kehu_list'
    template_name = "kehu_del.html"

class KehuUpdateView(LoginRequiredMixin, UpdateView):
    model = KeHu
    form_class = KeHuForm
    template_name = 'kehu_up.html'

    def get_success_url(self):
        success_url = reverse_lazy('Kehu_detail', kwargs={'pk': self.object.id})
        return success_url

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        kehu_obj = self.get_object()
        try:
            zilao_obj = kehu_obj.kehuzilao
            context['zilao_form'] = KeHuzilaoForm(instance=zilao_obj, prefix='zilao')
        except KeHuzilao.DoesNotExist:
            context['zilao_form'] = KeHuzilaoForm(prefix='zilao')
        return context

    def form_valid(self, form):
        # 保存表单等操作...
        self.object = form.save()
        # 返回一个JsonResponse给Ajax调用者
        response_data = {'message': '表单提交成功！', 'status': 'success'}  # 自定义返回信息 status -》success 告诉前端提交成功
        return JsonResponse(response_data)  # 返回JSON响应而不是重定向

class KeHuZilaoCreateOrUpdate(LoginRequiredMixin, CreateView):
    model = KeHuzilao
    form_class = KeHuzilaoForm
    template_name = 'kehu_detail.html'

    def get_success_url(self):
        success_url = reverse_lazy('Kehu_detail', kwargs={'pk': self.object.id})
        return success_url

    def dispatch(self, request, *args, **kwargs):
        self.kehu = get_object_or_404(KeHu, pk=kwargs['pk'])
        return super().dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        form.instance.kehu = self.kehu
        response = super().form_valid(form)
        return response

class KehuDetail(LoginRequiredMixin, DetailView):
    """客户详情"""
    template_name = 'kehu_detail.html'
    extra_context = {'title': '客户信息详情'}
    model = KeHu
    context_object_name = 'khxq'
    bigtitle = "客户管理"

    def get(self, request, *args, **kwargs):
        self.object = self.get_object()  # 获取当前客户对象
        print(f"Received POST data for {self.object}: {request}{request.GET}:{kwargs}")
        context = self.get_context_data(object=self.object)  # 初始化上下文将对象进行填充
        context['genjinlog_form'] = KeHugenjinlogForm()  # 添加空表单到上下文
      #  context['KeHuzilao_Form'] = KeHuzilaoForm()  # 添加空表单到上下文
        context['kehuzhuangtai'] = KeHu_zhaungtaiForm()  # 客户状态表单
        context['KeHu_Form'] = KeHuForm(
            instance=self.object, data=request.POST or None,
            is_update=True)  # 修复更新与新增的tel判断
        context['xueyuan_form'] = Xueyuan_zongbiao()
        # zhanneixin_index(f"{self.request.user}为该学员已是老客户,又新增了订单",
        #                  self.request.user,self.request.user)
        return self.render_to_response(context)

    def post(self, request, *args, **kwargs):
        self.object = self.get_object()
        form_key = request.POST.get('form_key')
        forms = {
            'genjinlog': KeHugenjinlogForm(request.POST),
          #  'ziliao': KeHuzilaoForm(request.POST, request.FILES),
            'kehuzhaungtai': KeHu_zhaungtaiForm(request.POST, request.FILES)
        }
        redirect_url = reverse('Kehu_detail', kwargs={'pk': self.object.id})
        query_params = {
            'genjinlog': '#v-pills-settings',
        #    'ziliao': '#v-pills-xiangqing',
            'dingdan': '#v-pills-profile',
        }.get(form_key, '#v-pills-home')

        if form_key and form_key in forms:
            form = forms[form_key]
            if form.is_valid():
                instance = form.save(commit=False)
                instance.kehu = self.object

                # if form_key == 'ziliao':
                #     try:
                #         existing_instance = KeHuzilao.objects.get(kehu=self.object)
                #         # 更新现有实例
                #         for field in ['hujileixing', 'hujizhenghao', 'fujian']:
                #             if field in form.cleaned_data:
                #                 setattr(existing_instance, field, form.cleaned_data[field])
                #         instance = existing_instance
                #     except KeHuzilao.DoesNotExist:
                #         # 新建实例
                #         pass  # 这里原本没有新建实例的代码，需要添加

                # 注意：对于 genjinlog 的额外处理应该放在这里，而不是再次验证 form
                if form_key == 'genjinlog':
                    instance.genjin_user = request.user

                instance.save()

        return redirect(f'{redirect_url}{query_params}')
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['bigtitle'] = self.bigtitle
        kehu_obj = self.object
        # 添加当前客户的跟进记录列表到上下文
        genjinlogs = KeHugenjinlog.objects.filter(kehu=kehu_obj).order_by(
            '-genjintime')  # 在KeHugenjinlog模型中查询kehu=kehu_obj的记录 .order_by('genjintime')默认为升序，加-为降序
        context['genjinlogs'] = genjinlogs
      #  kehuziliaos = KeHuzilao.objects.filter(kehu=kehu_obj)#客户资料
      #  context['kehuziliaos'] = kehuziliaos
        kehudingdans = Dingdan.objects.filter(kehu=kehu_obj).order_by('-ddtime')
        context['kehudingdans'] = kehudingdans
        ###admin权限判断
        user = self.request.user
        user_permissions = list(user.get_all_permissions())
        is_admin = user.is_superuser
        context['user_permissions'] = user_permissions
        context['is_admin'] = is_admin
        context['jiaowulog'] = xueyuan_jiaowu_genjinlog.objects.filter(kehu__kehu=kehu_obj)
        print(context['jiaowulog'])
        return context

class genjinlogsDeleteView(LoginRequiredMixin, DeleteView):
    """删除跟进记录"""
    model = KeHugenjinlog
    template_name = "KeHugenjinlog_del.html"
    context_object_name = 'log_entry'  # 可选，用于在模板中引用对象
    success_url_name = 'Kehu_detail'  # 用于反转的 URL 名称

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = "确定删除这条跟进记录?"  # 直接在视图中设置标题
        return context

    def get_success_url(self):
        success_url = reverse(self.success_url_name, kwargs={'pk': self.object.kehu.id})
        query_params = '#v-pills-settings'
        return f'{success_url}{query_params}'

class kehudingdanDeleteView(LoginRequiredMixin, DeleteView):
    model = Dingdan
    template_name = "dingdan_del.html"
    context_object_name = 'log_entry'  # 可选，用于在模板中引用对象
    success_url_name = 'product_list'  # 用于反转的 URL 名称

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = "确定删除这条订单?"  # 直接在视图中设置标题
        return context

    def get_success_url(self):
        success_url = reverse(self.success_url_name, kwargs={'pk': self.object.kehu.id})
        query_params = '#v-pills-profile'
        return f'{success_url}{query_params}'

class Kehu_zt_update(LoginRequiredMixin, UpdateView):
    model = KeHu_zhaungtai
    form_class = KeHu_zhaungtaiForm
    template_name = 'kehu_zhuangtaiup.html'

    def form_valid(self, form):
        # 保存表单等操作...
        print(form.cleaned_data)
        self.object = form.save()
        # 返回一个JsonResponse给Ajax调用者
        response_data = {'message': '表单提交成功！', 'status': 'success'}  # 自定义返回信息 status -》success 告诉前端提交成功
        return JsonResponse(response_data)  # 返回JSON响应而不是重定向

    def form_invalid(self, form):
        # 处理无效的表单提交情况...
        response_data = {'errors': form.errors, 'status': 'failure'}  # 自定义返回信息 status -》failure 告诉前端提交失败
        return JsonResponse(response_data, status=400)

class kehulist(LoginRequiredMixin, ListView):
    ###客户列表
    model = KeHu
    template_name = "kehu_list.html"
    context_object_name = 'kehu_list'
    bigtitle = "客户管理"
    smtitle="客户列表"
    paginate_by = 10
    ordering = ['addtime']


    # 定义一个名为 get_queryset 的方法，通常这个方法在 Django 的视图集（ViewSet）或视图（View）中用于获取查询集
    def get_queryset(self):
        # 获取当前的用户
        current_user = self.request.user
        search_term = self.request.GET.dict()  # 将 QueryDict 转换为普通字典
        queryset = KeHu.objects.all()
        queryset = search_kehu(queryset, search_term, current_user)
        print(f"queryset-----------{queryset}")
        # 判断当前用户是否为超级用户
        if current_user.is_superuser:
            # 如果是超级用户，返回过滤后的查询集（超级用户可以查看所有记录）
            return queryset.order_by('-addtime')
        else:
            # 如果不是超级用户，只返回过滤后且 admin_user 字段等于当前用户的记录（非超级用户只能查看自己的记录）
            return queryset.filter(admin_user=current_user).order_by('-addtime')

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['bigtitle'] = self.bigtitle
        context['smtitle'] = self.smtitle
        context['search'] = self.request.GET.get('search', '')
        context['admin_user'] = User.objects.all()

        kehu_with_last_genjin = []
        for kehu in context['kehu_list']:
            last_genjinlog = KeHugenjinlog.objects.filter(kehu=kehu).order_by('genjintime').first()
            order_count = Dingdan.objects.filter(kehu=kehu).count()
            ifhasdds = order_count
            last_genjin_time = last_genjinlog.genjintime if last_genjinlog else f"暂无跟进记录"
            kehu_with_last_genjin.append((kehu, last_genjin_time, ifhasdds))

        context['kehu_list_with_last_genjin'] = kehu_with_last_genjin
        context['tudao_list'] = tg_qudao.objects.all()
        page = context['page_obj']
        context['has_previous'] = page.has_previous()
        context['has_next'] = page.has_next()
        context['previous_page_number'] = page.previous_page_number() if page.has_previous() else None
        context['next_page_number'] = page.next_page_number() if page.has_next() else None
        return context

class my_hasdd_kehu(LoginRequiredMixin, ListView):
    model = KeHu
    template_name = 'kehu_list.html'
    context_object_name = 'kehu_list'
    bigtitle = "客户管理"
    smtitle="成交客户"
    paginate_by = 8
    ordering = ['-addtime']  # 按照addtime降序排列



    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['admin_user'] = User.objects.all()
        context['bigtitle']=self.bigtitle
        context['smtitle'] = self.smtitle
        context['search'] = self.request.GET.get('search', '')
        context['admin_user'] = User.objects.all()
        # 为每个客户添加最后跟进时间
        kehu_with_last_genjin = []
        for kehu in context['kehu_list']:
            # 获取当前客户的最后跟进记录
            last_genjinlog = KeHugenjinlog.objects.filter(kehu=kehu).order_by('genjintime').first()
            # 查询当前客户是否有订单 exists()方法会返回一个布尔值 count()反馈统计数量
            order_count = Dingdan.objects.filter(kehu=kehu).count()
            # 将查询结果转换为1或0，并赋值给ifhasdds
            ifhasdds = order_count
            # 如果存在跟进记录，则获取最后跟进时间，否则设置为None
            last_genjin_time = last_genjinlog.genjintime if last_genjinlog else f"暂无跟进几记录"
            # 将客户和最后跟进时间作为一个元组添加到新列表中
            kehu_with_last_genjin.append((kehu, last_genjin_time, ifhasdds))
        context['kehu_list_with_last_genjin'] = kehu_with_last_genjin
        context['tudao_list'] = tg_qudao.objects.all()

        # 分页
        page = context['page_obj']
        context['has_previous'] = page.has_previous()
        context['has_next'] = page.has_next()
        context['previous_page_number'] = page.previous_page_number() if page.has_previous() else None
        context['next_page_number'] = page.next_page_number() if page.has_next() else None
        print(context['kehu_list'])
        return context

    def get_queryset(self):
        current_user = self.request.user
        # 获取当前登录的用户
        # 使用集合来存储拥有订单的客户ID
        customers_with_orders = set()
        if current_user.is_superuser:
            kehulist = KeHu.objects.filter(if_gonghai=0).order_by('-addtime')
        else:
            kehulist = KeHu.objects.filter(admin_user=current_user, if_gonghai=0).order_by('-addtime')  # 过滤出当前用户的数据

        for kehu in kehulist:
            if Dingdan.objects.filter(kehu=kehu).exists():
                customers_with_orders.add(kehu.id)
                # 过滤出拥有订单的客户

        # 使用列表推导式来创建一个包含 KeHu 对象的查询集
        filtered_kehu_list = KeHu.objects.filter(id__in=customers_with_orders)
        print(filtered_kehu_list)
        if not filtered_kehu_list:
            filtered_kehu_list = []
        return filtered_kehu_list


class My_Nodd_Kehu(LoginRequiredMixin, ListView):
    model = KeHu
    template_name = 'kehu_list.html'
    context_object_name = 'kehu_list'
    bigtitle = "客户管理"
    smtitle="未报名客户"
    paginate_by = 8
    ordering = ['-addtime']  # 按照addtime降序排列

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['admin_user'] = User.objects.all()
        context['search'] = self.request.GET.get('search', '')
        context['admin_user'] = User.objects.all()
        context['bigtitle'] = self.bigtitle
        context['smtitle'] = self.smtitle
        # 为每个客户添加最后跟进时间
        kehu_with_last_genjin = []
        for kehu in context['kehu_list']:
            # 获取当前客户的最后跟进记录
            last_genjinlog = KeHugenjinlog.objects.filter(kehu=kehu).order_by('genjintime').first()
            # 查询当前客户是否有订单 exists()方法会返回一个布尔值 count()反馈统计数量
            order_count = Dingdan.objects.filter(kehu=kehu).count()
            # 将查询结果转换为1或0，并赋值给ifhasdds
            ifhasdds = order_count
            # 如果存在跟进记录，则获取最后跟进时间，否则设置为None
            last_genjin_time = last_genjinlog.genjintime if last_genjinlog else f"暂无跟进几记录"
            # 将客户和最后跟进时间作为一个元组添加到新列表中
            kehu_with_last_genjin.append((kehu, last_genjin_time, ifhasdds))
        # 将新列表添加到上下文中，替换原始的客户列表
        context['kehu_list_with_last_genjin'] = kehu_with_last_genjin
        context['tudao_list'] = tg_qudao.objects.all()
        # 分页
        page = context['page_obj']
        context['has_previous'] = page.has_previous()
        context['has_next'] = page.has_next()
        context['previous_page_number'] = page.previous_page_number() if page.has_previous() else None
        context['next_page_number'] = page.next_page_number() if page.has_next() else None
        print(context['kehu_list'])
        return context

    def get_queryset(self):
        # 获取当前登录的用户
        queryset = super().get_queryset()
        print(queryset)
        current_user = self.request.user
        # object_list=self.queryset
        customers_with_orders = set()

        filtered_kehu_list = []  # 在函数开始处初始化 filtered_kehu_list
        if current_user.is_superuser:
            for kehu in KeHu.objects.filter(if_gonghai=0).order_by('-addtime'):
                if not Dingdan.objects.filter(kehu=kehu).exists():
                    customers_with_orders.add(kehu.id)
            filtered_kehu_list = [kehu for kehu in queryset if kehu.id in customers_with_orders]
            print(filtered_kehu_list)
        else:
            for kehu in KeHu.objects.filter(admin_user=current_user, if_gonghai=0).order_by('-addtime'):
                if not Dingdan.objects.filter(kehu=kehu).exists():
                    customers_with_orders.add(kehu.id)
            filtered_kehu_list = [kehu for kehu in queryset if kehu.id in customers_with_orders]
            print(filtered_kehu_list)

        return filtered_kehu_list
            # return KeHu.objects.filter(admin_user=current_user, if_gonghai=0).order_by('-addtime')  # 过滤出当前用户的数据


